/**
 * 添加编辑快递信息
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, DatePicker, Select, Tooltip, Icon, Button, InputNumber, message } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import styles from './index.less';
import moment from 'moment';

import { Const } from '../../Const';
import {
  savePkgExpressOrder,
  batchUpdateImg,
  getPkgAccidentDetail
} from '../service';

import PicUpload from '../../lessBaggageManagement/components/PicUpload';
import ShowPic from '../../lessBaggageManagement/components/ShowPic';
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

class PrivateData {
  static titleMap = new Map()
    .set('add', '新增')
    .set('edit', '编辑')
    .set('view', '查看');
}

const AddEditExpress = props => {

  const { modalVisible, onCancel, form, onSubmit, itemData, detailData, type, ownerType } = props;

  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false); // PicUpload
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false); // ShowPic
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  });
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([]);

  // 保存快递
  const { run: runSavePkgExpressOrder } = useRequest(data => savePkgExpressOrder(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '保存快递');
      onSubmit();
    }
  });

  // 事故单详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '事故单详情');
      let data = res || {};
      let imgArr = data.pkgImgList || [];
      handleOriginPicArr(imgArr);
      let goodFileListData = imgArr.filter(item => {
        return item.oneType === 1
      });

      let touristFileListData = imgArr.filter(item => {
        return item.oneType === 2
      });

      let paperFileListData = imgArr.filter(item => {
        return item.oneType === 3
      });

      let luggageFileListData = imgArr.filter(item => {
        return item.oneType === 4
      });

      handleLostItemPicture({
        goodFileList: goodFileListData,
        touristFileList: touristFileListData,
        paperFileList: paperFileListData,
        luggageFileList: luggageFileListData,
      });
    }
  });

  // 批量修改图片
  const { run: runBatchUpdateImg } = useRequest(data => batchUpdateImg(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '批量修改图片');
      runGetPkgAccidentDetail({
        accidentId: itemData.accidentId
      });
      handleLostItemPicManageVisible(false);
      handleLostItemPicVisible(false);
    }
  });


  useEffect(() => {
    if (modalVisible) {
      runGetPkgAccidentDetail({
        accidentId: itemData.accidentId
      });
    }
  }, [itemData, modalVisible]);

  // 确定
  const okHandle = useCallback(() => {
    if (type === 'view') {
      onCancel();
      return;
    }
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.expressDateStr && fieldsValue.expressDateStr.isValid()) {
        fieldsValue.expressDateStr = fieldsValue.expressDateStr.format(Const.format);
      }
      if (type === 'edit') {
        if (detailData.id) {
          fieldsValue.id = detailData.id;
        } else {
          message.warning('编辑失败，未获取到快递信息ID');
        }
      }
      console.log(fieldsValue, 'fieldsValue');
      runSavePkgExpressOrder(fieldsValue);
    });
  }, [type, detailData]);

  // 新增图片、改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = itemData.accidentId
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr, ...lostItemPicNotIdArr])
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr]);
  }

  // 图片管理
  const imageManagement = useCallback(() => {
    handleLostItemPicManageVisible(true);
  }, [itemData]);

  const strNumValidator = useCallback((rule, value, callback) => {
    if (value) {
      if (Const.dealStrNum(value, 40)) {
        callback();
      } else {
        callback('最多输入40个字符');
      }
    } else {
      callback('');
    }
  }, [form]);

  // 备注 - 验证
  const remarkValidator = useCallback((rule, value, callback) => {
    if (value) {
      if (Const.dealStrNum(value, 120)) {
        callback();
      } else {
        callback('最多输入120个字符');
      }
    } else {
      callback();
    }
  }, [form]);

  // 收件地址 - 验证
  const recipientAddressValidator = useCallback((rule, value, callback) => {
    if (value) {
      if (Const.dealStrNum(value, 120)) {
        callback();
      } else {
        callback('最多输入120个字符');
      }
    } else {
      callback('');
    }
  }, [form]);

  return (
    <Modal
      destroyOnClose
      title={`${PrivateData.titleMap.get(type)}快递单`}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
    >
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="快递公司">
          {form.getFieldDecorator('expressCompany', {
            rules: [
              { required: true, message: '请选择快递公司' }
            ],
            initialValue: detailData.expressCompany || ''
          })(
            <Select
              allowClear
              disabled={type === 'view'}
              placeholder="请选择"
              style={{ width: '100%' }}>
              {Const.expressCompanyList.map((item, index) => <Option key={item} value={item}>{item}</Option>)}
            </Select>
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="快递单号">
          {form.getFieldDecorator('expressOrderId', {
            rules: [
              { required: true, message: '请输入快递单号' },
              { validator: strNumValidator }
            ],
            initialValue: detailData.expressOrderId || ''
          })(
            <Input placeholder="请输入" maxLength={40} disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="处理类型">
          {form.getFieldDecorator('accidentType', {
            rules: [],
            initialValue: Const.accidentTypeMap[+itemData.accidentType]?.text || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="事故单编号">
          {form.getFieldDecorator('accidentId', {
            rules: [],
            initialValue: itemData.accidentId || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="旅客姓名">
          {form.getFieldDecorator('paxName', {
            rules: [],
            initialValue: itemData.paxName || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="证件号">
          {form.getFieldDecorator('idNo', {
            rules: [],
            initialValue: itemData.idNo || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="航班号">
          {form.getFieldDecorator('flightNo', {
            rules: [],
            initialValue: itemData.flightNo || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="航班日期">
          {form.getFieldDecorator('flightDate', {
            rules: [],
            initialValue: itemData.flightDate || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="出发站">
          {form.getFieldDecorator('orgCityAirp', {
            rules: [],
            initialValue: itemData.orgCityAirp || ''
          })(
            <Input placeholder="请输入" disabled />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="收件人">
          {form.getFieldDecorator('expressRecipient', {
            rules: [
              { required: true, message: '请输入收件人' },
              { validator: strNumValidator }
            ],
            initialValue: detailData.expressRecipient || ''
          })(
            <Input placeholder="请输入" maxLength={40} disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="收件人电话1">
          {form.getFieldDecorator('recipientPhoneFirst', {
            rules: [
              { required: true, message: '请输入收件人电话1' },
              { pattern: Const.phoneMobileReg, message: '请输入正确的格式'}
            ],
            initialValue: detailData.recipientPhoneFirst || ''
          })(
            <Input placeholder="请输入" maxLength={11} disabled={type === 'view'} />
          )}
        </FormItem>
        <FormItem {...Const.formLayout} label="收件人电话2">
          {form.getFieldDecorator('recipientPhoneSecond', {
            rules: [
              { pattern: Const.phoneMobileReg, message: '请输入正确的格式'}
            ],
            initialValue: detailData.recipientPhoneSecond || ''
          })(
            <Input placeholder="请输入" maxLength={11} disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="快递日期">
          {form.getFieldDecorator('expressDateStr', {
            rules: [
              { required: true, message: '请选择快递日期' }
            ],
            initialValue: detailData.expressDateStr ? moment(detailData.expressDateStr)  : moment()
          })(<DatePicker format={Const.format} placeholder="请选择日期" disabled style={{ width: '100%' }} />)}
        </FormItem>
        <FormItem {...Const.formLayout} label="行李号">
          {form.getFieldDecorator('pkgNo', {
            rules: [
              { required: true, message: '请输入行李号' },
              { pattern: /^([A-Z\d]{6}|[A-Z\d]{8}|[A-Z\d]{10})$/, message: '行李号不正确，正确格式如123456、AA123456、1234567890' },
            ],
            initialValue: itemData.pkgNo || ''
          })(
            <Input placeholder="请输入" maxLength={50} disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayout} label="快递重量" style={{ flex: '0 0 50%', width: '50%' }}>
          {form.getFieldDecorator('expressWeight', {
            rules: [],
            initialValue: detailData.expressWeight || ''
          })(
            <InputNumber
              min={0}
              max={Const.inputNumMax}
              placeholder="请输入"
              style={{ width: '100%' }}
              disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayoutTwo} label="收件人地址">
          {form.getFieldDecorator('recipientAddress', {
            rules: [
              { required: true, message: '请输入收件地址' },
              { validator: recipientAddressValidator }
            ],
            initialValue: detailData.recipientAddress || ''
          })(
            <TextArea placeholder="请输入" autoSize={{ minRows: 3, maxRows: 3 }} maxLength={120} disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <FormItem {...Const.formLayoutTwo} label="备注">
          {form.getFieldDecorator('remark', {
            rules: [
              { validator: remarkValidator }
            ],
            initialValue: detailData.remark || ''
          })(
            <TextArea placeholder="请输入" autoSize={{ minRows: 3, maxRows: 3 }} maxLength={120} disabled={type === 'view'} />
          )}
        </FormItem>
      </div>
      <div className={styles.formContent}>
        <Button type="primary" onClick={imageManagement}>图片管理</Button>
      </div>
      {lostItemPicVisible && <PicUpload
        onSubmit={async value => {
          const success = await handleImgs(value)
        }}
        onCancel={() => handleLostItemPicVisible(false)}
        lostItemPicVisible={lostItemPicVisible}
        lostItemPic={lostItemPic}
        ownerType={10}
      ></PicUpload>}
      {lostItemPicManageVisible && <ShowPic
        onSubmit={async value => {
          const success = await handleDelImgs(value)
        }}
        toUpload={(value) => {
          handleLostItemPicture(value)
          handleLostItemPicManageVisible(false)
          handleLostItemPicVisible(true)
        }}
        onCancel={() => handleLostItemPicManageVisible(false)}
        lostItemPicManageVisible={lostItemPicManageVisible}
        lostItemPic={lostItemPic}
        ownerType={10}
        status={type === 'view' ? 'view' : itemData.status}
      ></ShowPic>}
    </Modal>
  )
}

export default Form.create()(AddEditExpress);
